<template>
  <template v-for="element in fakeItems" :key="element.id">
    <item
      ref="item"
      :attrs="element.attrs"
      :extend-attrs="element.extendAttrs"
      :form="form"
      :properties="element.properties"
      :children="element.children"
      :type="element.type"
      :disable-item="disableItem"
      @change="
        (v) => {
          $emit('change', v)
        }
      "
    >
      <template #item="{ properties, type }">
        <slot name="item" :properties="properties" :type="type"></slot>
      </template>
    </item>
  </template>
</template>

<script>
import Item from './item/index.vue'
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'DynamicForm',
  components: { Item },
  model: {
    prop: 'items'
  },
  props: {
    form: Object,
    disableItem: {
      type: Boolean,
      required: false,
      default: () => {
        return false
      }
    },
    items: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  emits: ['change'],
  data() {
    return { fakeItems: this.items }
  },
  watch: {
    items: {
      handler: function (val, oldVal) {
        this.fakeItems = val
      },
      deep: true
    }
  },
  methods: {
    isShow(properties) {
      if (properties.ifCondition) {
        // eslint-disable-next-line no-eval
        return eval('(formValue,$hasRole,$hasPermission)=>{return ' + properties.ifCondition + '}')(
          this.form,
          this['$hasRole'],
          this['$hasPermission']
        )
      }
      return true
    },
    getRef(id) {
      return this.$refs[id]
    },
    getRefByKey(key) {
      var item = this.fakeItems.find((item) => {
        return item.properties.key == key
      })
      if (!item) {
        for (let i = 0; i < this.fakeItems.length; i++) {
          item = this.getRef(this.fakeItems[i].id).getRefByKey(key)
        }
      }
      return item
    }
  }
})
</script>
